using System;
using System.Collections.Generic;
using Common.Logging;
using NServiceBus.Management.Messages.Tracking;
using NServiceBus.Unicast.Transport;

namespace NServiceBus.Management.Managers.Impl
{
    public class TrackingManager : ManagerBase,
                                   ITrackingManager
    {
        private readonly IList<EnableTrackingCommand> trackedMessages = new List<EnableTrackingCommand>();
        private static readonly ILog logger = LogManager.GetLogger(typeof(EndpointManager));

        public override ITransport Transport
        {
            get
            {
                return base.Transport;
            }
            set
            {
                base.Transport = value;

                //subscribe for transport events
                base.Transport.TransportMessageReceived += HandleTransportMessageReceived;

            }
        }

        public IList<EnableTrackingCommand> TrackedMessages
        {
            get
            {
                return trackedMessages;

            }
        }

        private bool IsTrackingEnabledFor(string name)
        {
            lock (trackedMessages)
                foreach (EnableTrackingCommand msg in trackedMessages)
                {
                    if (msg.MessageToTrack == name)
                        return true;
                }

            return false;
        }

        private EnableTrackingCommand FindTrackingMessage(Type t)
        {
            lock (trackedMessages)
            {
                foreach (EnableTrackingCommand msg in trackedMessages)
                {
                    if (msg.MessageToTrack == t.Name)
                        return msg;
                }
            }
            return null;
        }

        private void HandleTransportMessageReceived(object sender, TransportMessageReceivedEventArgs eventArgs)
        {
            foreach (object message in eventArgs.Message.Messages)
            {
                EnableTrackingCommand msg = FindTrackingMessage(message.GetType());
                if (msg != null)
                {
                    TransportMessage tr = eventArgs.Message;

                    if (!msg.TrackBody)
                        if(tr.BodyStream != null)
                            tr.BodyStream.Close();

                    Bus.Send(new TrackingDataMessage { TrackedMessage = tr });

                    logger.Debug("Tracking information for messagetype: " + message.GetType());
                    return;
                }
            }
        }


        public void EnableTrackingFor(EnableTrackingCommand commandTypeToTrack)
        {
            lock (trackedMessages)
            {

                if (!IsTrackingEnabledFor(commandTypeToTrack.MessageToTrack))
                    trackedMessages.Add(commandTypeToTrack);
            }
        }

    }
}